package controllers.admin.permission;

import controllers.deadbolt.RestrictedResource;
import models.common.CodeStatus;
import models.permission.Menu;
import play.modules.router.Get;
import play.modules.router.Post;
import play.mvc.Controller;
import utils.JSON;
import utils.R;
import utils.query.Page;
import utils.query.QueryHelper;

import java.util.List;

/**
 * 菜单管理
 */
@RestrictedResource(name="/tts/sys/menu/index")
public class Resources extends Controller {

	@Get("/tts/sys/menu/index")
	public static void index(){
		render();
	}

	/*
	 * 查询
	 */
	@Get("/tts/sys/menu/list")
	public static void list() {
		Page page = QueryHelper.getPageResults(Menu.class);
		R r = R.ok().putPage(page);
		String json = JSON.customExpose().toJson(r);
		renderJSON(json);
	}

	@Get("/tts/sys/menu/info/{<[0-9]+>id}")
	public static void info(Long id){
		Menu menu = Menu.findById(id);
		R r = R.ok().put("menu",menu);
		renderJSON(JSON.customExpose().toJson(r));
	}


	/**
	 * 返回Json tree 供页面Ztree 插件调用
	 */
	@Get("/tts/sys/menu/select")
	public static void treeJson() {
		List<Menu> menus = Menu.getTopLevel();

		R r = R.ok().put("menuList",menus);
		renderJSON(JSON.customExpose().toJson(r));
	}
	/*
	 * 添加后保存
	 */
	@Post("/tts/sys/menu/save")
	public static void create(Menu t ) {
		try{
			t.save();
		}catch (Exception e){
			throw new RuntimeException(e.getMessage());
		}
		R r = R.ok();
		renderJSON(r);
	}

	/*
	 * 禁用
	 */
	@Post("/tts/sys/menu/invalid")
	public static void invalid(Long[] id) {
		for (Long aId: id) {
			Menu resource = Menu.findById(aId);
			if(resource!=null) {
				resource.status = CodeStatus.INVALID;
				resource.save();
			}
		}
		R r = R.ok();
		renderJSON(JSON.customExpose().toJson(r));
	}

	/*
	 * 启用
	 */
	@Post("/tts/sys/menu/valid")
	public static void valid(Long[] id) {
		for (Long aId: id) {
			Menu resource = Menu.findById(aId);
			if(resource!=null) {
				resource.status = CodeStatus.VALID;
				resource.save();
			}
		}
		R r = R.ok();
		renderJSON(JSON.customExpose().toJson(r));
	}

}
